package com.jackrain.nea.fc.pos.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.common.PostDubbleEvent;
import com.jackrain.nea.common.QueryUserUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.pos.api.ViewDLRetailStoTimeUpCmd;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 零售单修改日期
 *
 * @author zhang.zz
 * @date 2018/11/26
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "pos")
public class ViewDLRetailStoTimeUpCmdImpl extends CommandAdapter implements ViewDLRetailStoTimeUpCmd {

    @Autowired
    PostDubbleEvent postDubbleEvent;

    @Autowired
    private QueryUserUtil queryUserUtil;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"),
                "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewDLRetailStoTimeUpCmdImpl-->param-->{}",param);

        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }

        JSONArray paramArray = param.getJSONArray("data");
        log.debug("ViewDLRetailStoTimeUpCmdImpl--paramArray-->{}",paramArray);
//        log.debug("date------------>"+paramArray);
        JSONArray errorArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();
        JSONArray successIds = new JSONArray();
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject errorJson = new JSONObject();
            JSONObject tranJson = paramArray.getJSONObject(i);

            JSONObject storeJson = tranJson.getJSONObject("TABLE_STORE_TIME_NAME");
//            log.debug("storeJson------------>"+storeJson);
            try {
                /*******处理数据********/
                JSONObject fixcolumn = new JSONObject();

                String bill_no = storeJson.getString("BILL_NO");
                String time_date = storeJson.getString("TIME");
                String oprEcode = storeJson.getString("OPR_ECODE");

                fixcolumn.put("BILL_NO", bill_no);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date =  new Date(Long.valueOf(time_date));
                String time = sdf.format(date);
                fixcolumn.put("TIME", time);

                User user = queryUserUtil.getUser(oprEcode);
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("dlreatilStoBill",
                        new HashMap(16));
//                log.debug("fixcolumn_data------->" + fixcolumn);
                accesLogger.info("ViewDLRetailStoTimeUpCmdImpl--fixcolumn-->{}",fixcolumn);

                event.put("param", fixcolumn);
                querySession.setEvent(event);
                String addNotic = "com.jackrain.nea.retail.api.BRetailChangeDateCmd:1.0:pos";
                //调用标准服务
                JSONObject retAddJo = postDubbleEvent.executePostDubble(addNotic, querySession);
//                log.debug("retAddJo------------>" + retAddJo);
                accesLogger.info("ViewDLRetailStoTimeUpCmdImpl--retAddJo-->{}",retAddJo);

                if (retAddJo.containsKey("code") && (int) retAddJo.get("code") != 0) {
                    errorJson.put("key", bill_no);
                    if (null == retAddJo.get("message")) {
                        errorJson.put("message", "零售修改日期处理时报错");
                    } else {
                        errorJson.put("message", "零售修改日期处理时报错->" + retAddJo.get("message"));
                    }
                    errorArray.add(errorJson);
                    continue;
                }
                queryDataArray.add(fixcolumn);
                successIds.add(bill_no);
            } catch (Exception e) {
                String error = "";
                if ((e instanceof NDSException)) {
                    error = e.getMessage();
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    error = sw.toString();
                }
                String bill_no = storeJson.getString("BILL_NO");
                errorJson.put("key", bill_no);
                errorJson.put("message", error);
                errorArray.add(errorJson);
            }
        }

        if (errorArray.size() > 0) {
            vh.put("error", errorArray);
            vh.put("code", -1);
        } else {
            vh.put("code", 0);
        }
        vh.put("queryDataArray", queryDataArray);
        vh.put("successIds", successIds);
//        log.debug("vh--------->"+vh);
        return vh;
    }

}
